import React , { Component } from 'react';
import { Map, List, is } from 'immutable'
import { Relax } from 'iflux2'
import {Row, Col, Dropdown, Button,  Alert, Menu, Checkbox, Icon, Table, Pagination, Modal, message, Popconfirm} from 'antd';
import { Link } from 'react-router';
import SimpleSearch from '../../component/SimpleSearch.js'
import AdvanceSearch from '../../component/AdvanceSearch.js'
import ArticleDialog from '../../component/ArticleDialog'
import classNames from 'classnames'
import noop from 'util/noop'
import columns from '../../constants/articleColumns.js';
import { treeSectionsQL } from '../ql.js';
//import QueueAnim from 'rc-queue-anim'
import { PageSizeOptions } from 'constant/pagination'
@Relax
export default class Articles extends Component {
    static defaultProps = {
        domain:Map(),
        articles:List([]),//文章列表
        pagination:Map({}),//分页数据
        treeSections:treeSectionsQL,//保持与treedata相同的数据结构
        fetchArticle:noop,//获取单个文章详情
        fetchArticles:noop,//获取文章列表函数
        updateArticle:noop,//更新文章
        addArticle:noop,//添加文章
        deleteArticle:noop,//删除文章
        changePage:noop,//页面跳转
        changeSearchParam:noop,//保存查询参数
    }

    constructor(props) {
        super(props);
        
        this.state = ({
            isAdvanceSearch:false, //显示高级搜索
            visible:false,//弹出框显示
            //selectedRowKeys:[],//勾选
            loading:true,
            //activeId:'',
            article:Map({})
        });
    }

    componentWillReceiveProps(nextProps) {
        if(!is(this.props.domain,nextProps.domain)){
            //预览的地址发生变化
            this.columns = this.concatColumns(nextProps, columns)
        }
    }
    componentDidMount() {
        //拼接列
        this.columns = this.concatColumns(this.props, columns);

        this.fetchArticles();
    }

    render () {
        const { articles, pagination, treeSections } = this.props;
        const { loading , visible, article } = this.state;
        const page = {
            current:pagination.get('pageNum'),
            total:pagination.get('totalCount'),
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions:PageSizeOptions,
            showTotal(total) {
                return `共 ${total} 条`;
            },
            onShowSizeChange:this.handleSizeChange,
            onChange:this.handlePageChange
            
        }

        const formSearchClass = classNames("search-form",{
            "show-advance":this.state.isAdvanceSearch
        })
        return (
            <div>
                <div className={formSearchClass}>
                    <div className="simple-search" key="simple-search">
                        <SimpleSearch
                            onSearch={this.handleSearch}
                            placeholder="请输入文章标题"
                        />
                        <a href="javascript:;" onClick={this.toggleSearch} className="search-advance-switch">高级搜索</a>
                    </div>
                    <Row type="flex" justify="end">
                        <Col span={24}>
                            {
                                this.state.isAdvanceSearch ? [
                                    <div className="advance-search" key="searchAdvance">
                                    <AdvanceSearch
                                        key="searchAdvance" 
                                        onSearch={this.handleSearch} 
                                        sections={treeSections}
                                        onToggle={this.toggleSearch}
                                    />
                                  </div>

                                ] : null
                            }
                        </Col>
                    </Row>
                </div>
                <Row className="table-toolbar">
                    <Col span={12}>
                        <Button type="primary" onClick={this.addArticle}>新增文章</Button>
                        <Link to="/article-section">
                            <Button type="ghost">文章栏目管理</Button>
                        </Link>

                    </Col>
                </Row>
                <Table
                    rowKey="id"
                    dataSource={articles.toJS()}
                    columns={this.columns}
                    loading={loading}
                    pagination={page}
                />
                <ArticleDialog
                    title={this.mode === 'add' ? "新增文章" : "编辑文章"}
                    visible={visible}
                    options={treeSections}
                    article={article}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                />
            </div>
        )
    }
    /**
     * 切换搜索模式
     * 简易，高级
     */
    toggleSearch = ()=>{
        this.setState({
            isAdvanceSearch:!this.state.isAdvanceSearch
        });
    }
    /**
     * 拼接列
     * 
     * 添加发布，操作列
     */
    concatColumns = (props, columns) => {
        const { domain } = props;
        return columns.concat([
            {
                title:"操作",
                key:"operation",
                render:(text,record,index)=>{
                    return (
                        <span className="operations">
                            <a href={`${domain.get('domainUrl')}/subject/${record.id}`} target="_blank">预览</a>
                            <a href="javascript:;" onClick={()=>{this.showDialog('update',record.id)}}>编辑</a>
                            <a href="javascript:;">
                            <Popconfirm placement="top" title={"您确定要删除该文章吗？"} onConfirm={()=>{this.confirmDelete(record,index)}} okText="确定" cancelText="取消">
                                <span>删除</span>
                            </Popconfirm>
                            </a>
                        </span>
                    )
                }
            }
        ])
    }

    // onSelectChange = (selectedRowKeys) => {
    //     this.setState({ selectedRowKeys });
    // }
    /**
     * 显示弹出框，查看|编辑文章
     */
    showDialog = (mode, activeId = '')=>{
        this.mode = mode;
        if(activeId){
            this.props.fetchArticle(activeId).then(article => {
                    this.setState({
                        article:Map(article)
                    });
                
            })
        }
        this.setState({
            visible:true,
        });
        
       
    }
    /**
     * 新增文章
     */
    addArticle = () => {
        this.showDialog('add');
    }
    /**
     * 批量删除
     */
    // batchDelete = () => {
    //     if(this.state.selectedRowKeys.length <= 0){
    //         return;
    //     }
    // }
    //搜索回调
    handleSearch = (values) => {
        this.props.changeSearchParam(values);
        this.props.changePage({pageNum:1})
        this.fetchArticles();
    }
    //搜索文章，调用store方法
    fetchArticles = () => {
        if(!this.state.loading){
            this.setState({
                loading:true
            })
        }

        this.props.fetchArticles()
        .then(()=>{
            this.setState({loading:false});
        })
        .catch(()=>{
            this.setState({loading:false})
        })
    }
    /**
     * 删除文章
     * @param article 文章
     * @param index 索引
     */
    confirmDelete = (article,index) => {
        this.props.deleteArticle(article.id);
    }

    /**
     * 每页显示商品条数变化
     */
    handleSizeChange = (current,pageSize) =>{
        this.props.changePage({pageNum:1,pageSize})
        this.fetchArticles()
    }
    /**
     * 跳转n页回调
     */
    handlePageChange = (pageNum,pageSize) => {
        this.props.changePage({pageNum})
        this.fetchArticles()
    }
    handleOk = (article) => {
        this.props[`${this.mode}Article`](article)
            .then(result => {
                this.handleCancel();
                this.fetchArticles();
            })
            .catch(error=>{

            });
    }
    handleCancel = () => {
        this.mode = '';
        this.setState({
            visible:false,
            article:Map({})
        });
    }
}